<template>
  <div class="app-container">
    <el-form
      ref="formData"
      :model="formData"
      status-icon
      label-position="left"
      label-width="100px"
      style="width: 800px; margin-left: 50px"
    >
      <el-form-item label="活动类型" prop="isNew">
        <el-radio-group v-model="formData.type">
          <el-radio :label="1">团购</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="活动标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="海报文案" prop="posterTitle">
        <el-input v-model="formData.posterTitle" />
      </el-form-item>
      <el-form-item label="分享链接文案" prop="shareTitle">
        <el-input v-model="formData.shareTitle" />
      </el-form-item>
      <el-form-item label="活动时间">
        <el-col :span="11">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="2" class="line">至</el-col>
        <el-col :span="11">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-col>
      </el-form-item>

      <el-form-item label="状态" prop="state">
        <el-select v-model="formData.state">
          <el-option label="待发布" value="0" />
          <el-option label="发布中" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="背景音乐" prop="isNew">
        <el-radio-group v-model="formData.musicUrl">
          <el-radio
            label="https://dyundyun.oss-cn-beijing.aliyuncs.com/oedzunj1nzs0q2dndtgd.mp3"
          >虫儿飞.mp3</el-radio>
          <el-radio
            label="https://dyundyun.oss-cn-beijing.aliyuncs.com/l2yrcq1sgjwickd8jnc7.mp3"
          >致爱丽丝.mp3</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="团购规则">
        <el-input
          v-model="subject"
          class="input-rule"
          clearable
          placeholder="请输入科目"
        />
        <el-input
          v-model="limited"
          class="input-rule"
          clearable
          placeholder="请填写参团人数"
        />
        <el-input
          v-model="origin"
          class="input-rule"
          clearable
          placeholder="请填写原价"
        />
        <el-input
          v-model="onsale"
          class="input-rule"
          clearable
          placeholder="请填写优惠价"
        />
        <el-button @click="handleAddRule()">添加</el-button>

        <el-table
          ref="ruleListTable"
          :data="formData.rulesList"
          style="width: 100%; margin-top: 20px"
          border
        >
          <el-table-column label="科目" align="center">
            <template slot-scope="scope">{{ scope.row.subject }}</template>
          </el-table-column>
          <el-table-column label="参团人数" align="center">
            <template slot-scope="scope">{{ scope.row.limited }}</template>
          </el-table-column>
          <el-table-column label="原价" align="center">
            <template slot-scope="scope">{{ scope.row.origin }}</template>
          </el-table-column>
          <el-table-column label="优惠价" align="center">
            <template slot-scope="scope">{{ scope.row.onsale }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleDeleteRule(scope.$index, scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="活动主图" prop="homePic">
        <el-upload
          :headers="headers"
          :action="uploadPath"
          :show-file-list="false"
          :on-success="homePicUrl"
          class="avatar-uploader"
          accept=".jpg,.jpeg,.png,.gif"
        >
          <img v-if="formData.homePic" :src="formData.homePic" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过1024kb
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="轮播图">
        <el-upload
          :action="uploadPath"
          :limit="10"
          :headers="headers"
          :on-exceed="slideshowPicLimit"
          :on-success="slideshowPicUrl"
          :on-remove="slideshowPicRemove"
          multiple
          accept=".jpg,.jpeg,.png,.gif"
          list-type="picture-card"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item
        label="游戏玩法"
        prop="gameRule"
      >
        <editor v-model="formData.gameRule" :init="editorInit" />
      </el-form-item>

      <el-form-item
        label="活动介绍"
        prop="acIntroduce.text"
      >
        <editor v-model="formData.acIntroduce.text" :init="editorInit" />
        <el-upload
          :action="uploadPath"
          :limit="10"
          :headers="headers"
          :on-exceed="acIntroducePicLimit"
          :on-success="acIntroducePicUrl"
          :on-remove="acIntroducePicRemove"
          accept=".jpg,.jpeg,.png,.gif"
          list-type="picture-card"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item
        label="机构介绍"
        prop="orgIntroduce.text"
      >
        <editor v-model="formData.orgIntroduce.text" :init="editorInit" />
        <el-upload
          :action="uploadPath"
          :limit="10"
          :headers="headers"
          :on-exceed="orgIntroducePicLimit"
          :on-success="orgIntroducePicUrl"
          :on-remove="orgIntroducePicRemove"
          accept=".jpg,.jpeg,.png,.gif"
          list-type="picture-card"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item
        label="奖品介绍"
        prop="goodsIntroduce.text"
      >
        <editor v-model="formData.goodsIntroduce.text" :init="editorInit" />
        <el-upload
          :action="uploadPath"
          :limit="5"
          :headers="headers"
          :on-exceed="goodsIntroducePicLimit"
          :on-success="goodsIntroducePicUrl"
          :on-remove="goodsIntroducePicRemove"
          accept=".jpg,.jpeg,.png,.gif"
          list-type="picture-card"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <!-- <el-form
        ref="formData"
        :inline="true"
        :model="formData"
        label-width="80px"
      >
        <div v-for="(item, index) in formData.dynamicItem" :key="item.id">
          <el-form-item
            label="介绍描述"
            :prop="'dynamicItem.' + index + '.textarea'"
            :rules="{
              required: true,
              message: '内容不能为空',
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="item.textarea"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <i class="el-icon-delete" @click="deleteItem(item, index)"></i>
          </el-form-item>
        </div>
      </el-form> -->

      <!-- <el-form-item>
        <el-button type="text" @click="addItem"> + 添加文本 </el-button>
      </el-form-item> -->
      <el-form-item
        label="机构地址"
        prop="address"
        :rules="{
          required: true,
          message: '内容不能为空',
          trigger: 'blur',
        }"
      >
        <el-input
          v-model="formData.address"
          class="input-rule-contact"
          clearable
          placeholder="机构联系地址"
        />
      </el-form-item>
      <el-form-item
        label="联系电话"
        prop="contactPhone"
        :rules="{
          required: true,
          message: '内容不能为空',
          trigger: 'blur',
        }"
      >
        <el-input
          v-model="formData.contactPhone"
          class="input-rule-contact"
          clearable
          placeholder="机构联系电话"
        />
      </el-form-item>
      <el-form-item
        label="联系邮箱"
        prop="email"
      >
        <el-input
          v-model="formData.email"
          class="input-rule-contact"
          clearable
          placeholder="机构联系邮箱"
        />
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </div>
</template>

<style>
.el-dialog {
  width: 800px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.input-rule {
  width: 140px;
  margin-left: 10px;
  vertical-align: bottom;
}

.input-rule-contact {
  width: 800px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

<script>
import { createActivity } from '@/api/activitylist'
import { uploadPath } from '@/api/storage'
// import BackToTop from '@/components/BackToTop'
import Editor from '@tinymce/tinymce-vue'
// import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getToken } from '@/utils/auth'

export default {
  name: 'ActivityCreate',
  components: { Editor },
  data() {
    return {
      origin: '',
      onsale: '',
      limited: '',
      subject: '',
      uploadPath,
      id: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      formData: {
        id: undefined,
        type: 1,
        title: '',
        posterTitle: '',
        shareTitle: '',
        startTime: '',
        endTime: '',
        musicUrl: '',
        homePic: '',
        slideshowPic: [],
        state: undefined,
        rulesList: [],
        address: '',
        contactPhone: '',
        email: '',
        gameRule: '',
        orgIntroduce: { text: '', pics: [] },
        acIntroduce: { text: '', pics: [] },
        goodsIntroduce: { text: '', pics: [] }
        // dynamicItem: [
        //  {
        //    id: "",
        //    textarea: "",
        //  },
        // ],
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        height: 300,
        plugins: [
          'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ]
      },
      list: [],
      total: 0,
      listLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {},
  methods: {
    handleCancel() {
      this.$router.push({ path: '/promotion/activity-list' })
    },
    handleConfirm() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          createActivity(this.formData)
            .then((response) => {
              this.$router.push({ path: '/promotion/activity-list' })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    // 首页图片上传数量限制
    homePicLimit: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传1张图片!'
      })
    },
    // 轮播图片上传数量限制
    slideshowPicLimit: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    // 机构介绍图片上传数量限制
    orgIntroducePicLimit: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传10张图片!'
      })
    },
    // 活动介绍图片上传数量限制
    acIntroducePicLimit: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传10张图片!'
      })
    },
    // 奖品介绍图片上传数量限制
    goodsIntroducePicLimit: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传2张图片!'
      })
    },
    // 首页图片存储
    homePicUrl(response) {
      this.formData.homePic = response.data.url
    },
    // 轮播图片存储
    slideshowPicUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.formData.slideshowPic.push(response.data.url)
      }
    },
    // 机构介绍图片存储
    orgIntroducePicUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.formData.orgIntroduce.pics.push(response.data.url)
      }
    },
    acIntroducePicUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.formData.acIntroduce.pics.push(response.data.url)
      }
    },
    goodsIntroducePicUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.formData.goodsIntroduce.pics.push(response.data.url)
      }
    },
    // 轮播图片移除
    slideshowPicRemove: function(file, fileList) {
      for (var i = 0; i < this.formData.slideshowPic.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.formData.slideshowPic[i] === url) {
          this.formData.slideshowPic.splice(i, 1)
        }
      }
    },
    // 机构介绍图片移除
    orgIntroducePicRemove: function(file, fileList) {
      for (var i = 0; i < this.formData.orgIntroduce.pics.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.formData.orgIntroduce.pics[i] === url) {
          this.formData.orgIntroduce.pics.splice(i, 1)
        }
      }
    },
    acIntroducePicRemove: function(file, fileList) {
      for (var i = 0; i < this.formData.acIntroduce.pics.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.formData.acIntroduce.pics[i] === url) {
          this.formData.acIntroduce.pics.splice(i, 1)
        }
      }
    },
    goodsIntroducePicRemove: function(file, fileList) {
      for (var i = 0; i < this.formData.goodsIntroduce.pics.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.formData.goodsIntroduce.pics[i] === url) {
          this.formData.goodsIntroduce.pics.splice(i, 1)
        }
      }
    },
    updateData() {},
    handleAddRule() {
      if (this.subject === null || this.subject.length === 0) {
        this.$message({
          message: '请填写科目',
          type: 'warning'
        })
        return
      }
      if (this.limited === null || this.limited.length === 0) {
        this.$message({
          message: '请填写参团人数',
          type: 'warning'
        })
        return
      }
      if (this.origin === null || this.origin.length === 0) {
        this.$message({
          message: '请填写原价',
          type: 'warning'
        })
        return
      }
      if (this.onsale === null || this.onsale.length === 0) {
        this.$message({
          message: '请填写优惠价',
          type: 'warning'
        })
        return
      }

      var params = {
        subject: this.subject,
        limited: this.limited,
        origin: this.origin,
        onsale: this.onsale,
        deleted: 0
      }

      this.formData.rulesList.push(params)
      this.subject = ''
      this.limited = ''
      this.origin = ''
      this.onsale = ''
      this.deleted = 0
    },
    handleDeleteRule(index, row) {
      this.formData.rulesList.splice(index, 1)
    }
    // addItem() {
    //  let array = {
    //    id: "",
    //    textarea: "",
    //  };
    //  this.formData.dynamicItem.push(array);
    // },
    // deleteItem(item, index) {
    //  this.formData.dynamicItem.splice(index, 1);
    // },
  }
}
</script>
